package cn.wowjoy.office.homepage;

import android.arch.lifecycle.MediatorLiveData;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.View;
import android.widget.Toast;

import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnItemLongClickListener;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.inject.Inject;

import cn.bingoogolapple.androidcommon.adapter.BGABindingRecyclerViewAdapter;
import cn.wowjoy.office.R;
import cn.wowjoy.office.appedit.AppEditActivity;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseViewModel;
import cn.wowjoy.office.baselivedata.appbase.NewMainApplication;
import cn.wowjoy.office.common.adapter.BannerAdapter;
import cn.wowjoy.office.common.adapter.ComAppAdapter;
import cn.wowjoy.office.data.remote.ApiService;
import cn.wowjoy.office.data.remote.ResultDataParse;
import cn.wowjoy.office.data.remote.RxSchedulerTransformer;
import cn.wowjoy.office.data.response.AppInfo;
import cn.wowjoy.office.data.response.BannerInfo;
import cn.wowjoy.office.databinding.ItemGridviewBinding;
import cn.wowjoy.office.qrcodescan.QrCodeScanActivity;
import cn.wowjoy.office.search.SearchActivity;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Created by Sherily on 2017/9/7.
 */

public class HomeViewModel extends NewBaseViewModel {

    public BannerAdapter bannerAdapter = new BannerAdapter();
    public BGABindingRecyclerViewAdapter<AppInfo, ItemGridviewBinding> winnerAdapter = new BGABindingRecyclerViewAdapter<>(R.layout.item_gridview);
    public LRecyclerViewAdapter wadapter = new LRecyclerViewAdapter(winnerAdapter);
    public List<AppInfo> wdatas;

    public ComAppAdapter comAppAdapter = new ComAppAdapter();


    @Inject
    public HomeViewModel(@NonNull NewMainApplication application) {
        super(application);
        winnerAdapter.setItemEventHandler(this);
    }

    @Override
    public void onCreateViewModel() {

    }

    private void setData(List<BannerInfo> bannerInfos){
        if (null == bannerAdapter)
            bannerAdapter = new BannerAdapter();
        bannerAdapter.setBannerInfos(bannerInfos);
    }
    private List<BannerInfo> createData(){
        List<BannerInfo> bannerInfos = new ArrayList<>();
        for (int i = 0; i < 4;i++){
            BannerInfo bannerInfo = new BannerInfo("http://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=%E5%BE%AE%E8%B7%9D%E6%91%84%E5%BD%B1&step_word=&hs=0&pn=4&spn=0&di=12470774410&pi=0&rn=1&tn=baiduimagedetail&is=3484402454%2C4083618241&istype=2&ie=utf-8&oe=utf-8&in=&cl=2&lm=-1&st=-1&cs=1517415098%2C4061300270&os=3204370208%2C171244297&simid=0%2C0&adpicid=0&lpn=0&ln=1911&fr=&fmq=1480332039000_R_D&fm=detail&ic=0&s=undefined&se=&sme=&tab=0&width=&height=&face=undefined&ist=&jit=&cg=&bdtype=17&oriquery=&objurl=http%3A%2F%2Fimg0.ph.126.net%2FeRv-A9o1L8v4MKZbiobhow%3D%3D%2F6608664116770962144.jpg&fromurl=ippr_z2C%24qAzdH3FAzdH3Fooo_z%26e3Bwtojtkwg2_z%26e3Bv54AzdH3Fy7j17AzdH3F9mlm9n_z%26e3Bip4s&gsm=&rpstart=0&rpnum=0");
            bannerInfos.add(bannerInfo);
        }
        return bannerInfos;
    }

    /**
     * banner mock data
     */
    public void request(){
        setData(createData());
    }

    /**
     * 相机扫码
     */
    public void scan(){
        Intent intent = new Intent(getApplication(), QrCodeScanActivity.class);
        getApplication().startActivity(intent);
    }

    /**
     * apps model mock data
     * @param data
     */
    public void setDatas(List<AppInfo> data) {
        if (null == wdatas)
            wdatas = new ArrayList<>();
        wdatas.clear();
        wdatas.addAll(data);
        comAppAdapter.setDatas(wdatas);
    }
    private List<AppInfo> createApps(){
        List<AppInfo> appInfos = new ArrayList<>();
        appInfos.add(new AppInfo("主数据",R.drawable.zhushuju_selector,false,1004));
        appInfos.add(new AppInfo("库存盘点", R.drawable.kucunpandian_selector,false,1001));
        appInfos.add(new AppInfo("库存详情",R.drawable.kucunxiangqing_selector,false,1003));
        appInfos.add(new AppInfo("巡检管理",R.drawable.inspection_res_selector,false,1002));
        appInfos.add(new AppInfo("设备盘点",R.drawable.material_res_selector,false,1011));
        appInfos.add(new AppInfo("其他出库",R.drawable.otherout_res_selector,false,1012));
        appInfos.add(new AppInfo("申领出库",R.drawable.shenling_res_selector,false,1013));
        appInfos.add(new AppInfo("申请出库",R.drawable.shenqing_res_selector,false,1014));
        appInfos.add(new AppInfo("调拨出库",R.drawable.inspection_res_selector,false,1015));
        appInfos.add(new AppInfo("PM管理",R.drawable.pm_res_selector,false,1016));
//         appInfos.add(new AppInfo("更多",R.drawable.more_res_selector,false,1011));
 //        appInfos.add(new AppInfo("敬请期待",R.drawable.more_res_selector,false,1005));
         appInfos.add(new AppInfo("维修申请",R.drawable.maintanece_res_selector,false,1003));
        return appInfos;
    }
    public void myAppinfos(){
       setDatas(createApps());
    }


    public void handleAppInfo(int position){
        if(position == (wdatas.size() - 1)){
            //需要定义一个pushUtil进行应用的跳转
            Intent intent = new Intent(getApplication(), AppEditActivity.class);
            getApplication().startActivity(intent);
        }
    }

    /**
     * 应用搜索
     */
    public void search(){
        Intent intent = new Intent(getApplication(), SearchActivity.class);
        getApplication().startActivity(intent);
    }


    /**
     * 应用编辑页面
     */
    public void jumpMore(){
        Intent intent = new Intent(getApplication(), AppEditActivity.class);
        getApplication().startActivity(intent);
    }



    public ItemTouchHelper getItemTouchHelper(){
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
                    final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN |
                            ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                    final int swipeFlags = 0;
                    return makeMovementFlags(dragFlags, swipeFlags);
                } else {
                    final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                    final int swipeFlags = 0;
//                    final int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
                    return makeMovementFlags(dragFlags, swipeFlags);
                }
            }

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                //得到当拖拽的viewHolder的Position
                int fromPosition = viewHolder.getAdapterPosition();
                //拿到当前拖拽到的item的viewHolder
                int toPosition = target.getAdapterPosition();
                if (fromPosition < toPosition) {
                    for (int i = fromPosition - 1; i < toPosition - 1; i++) {
                        Collections.swap(wdatas, i, i + 1);
                    }
                } else {
                    for (int i = fromPosition - 1; i > toPosition - 1; i--) {
                        Collections.swap(wdatas, i, i - 1);
                    }
                }
                wadapter.notifyItemMoved(fromPosition, toPosition);
                return true;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {

            }
            /**
             * 重写拖拽可用
             * @return
             */
            @Override
            public boolean isLongPressDragEnabled() {
                return false;
            }

            /**
             * 长按选中Item的时候开始调用
             *
             * @param viewHolder
             * @param actionState
             */
            @Override
            public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
                if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
                    viewHolder.itemView.setBackgroundColor(Color.LTGRAY);
                }
                super.onSelectedChanged(viewHolder, actionState);
            }

            /**
             * 手指松开的时候还原
             * @param recyclerView
             * @param viewHolder
             */
            @Override
            public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                super.clearView(recyclerView, viewHolder);
                viewHolder.itemView.setBackgroundColor(0);
            }
        });
        return itemTouchHelper;
    }
    public void setEventListener(){
        wadapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Toast.makeText(getApplication(),""+position,Toast.LENGTH_SHORT).show();

                if(position == (wdatas.size() - 1)){
                    Intent intent = new Intent(getApplication(), AppEditActivity.class);
                    getApplication().startActivity(intent);
                }
            }
        });
        wadapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public void onItemLongClick(View view, int position) {
                Toast.makeText(getApplication(),"请点击更多跳转至编辑页面编辑应用",Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void setAppInfoData(List<AppInfo> data) {
        if (null == wdatas)
            wdatas = new ArrayList<>();
        wdatas.clear();
        wdatas.addAll(data);
        winnerAdapter.setData(wdatas);
        wadapter.removeFooterView();
        wadapter.removeHeaderView();
        wadapter.notifyDataSetChanged();
    }
    @Inject
    ApiService mApiService;
    //获取首页菜单展示
    MediatorLiveData<LiveDataWrapper<List<AppInfo>>> mParams = new MediatorLiveData<>();
    public  void getAuidsPms(){
        mParams.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = mApiService.getAuidsPms()
                .flatMap(new ResultDataParse<List<AppInfo>>())
                .compose(new RxSchedulerTransformer<List<AppInfo>>())
                .subscribe(new Consumer<List<AppInfo>>() {
                    @Override
                    public void accept(List<AppInfo> taskListResponse) throws Exception {
                        mParams.setValue(LiveDataWrapper.success(taskListResponse));
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        mParams.setValue(LiveDataWrapper.error(throwable,null));
                    }
                });
        addDisposable(disposable);
    }


}
